import React, { Component } from 'react'
import {myGet, myPost} from '../fetch'

export default class Axios extends Component {
  constructor() {
    super()
    this.state = {
      muenList: []
    }
  }
  getData1() {
    this.http.get('/api/menulist')
    .then(res => {
      console.log(res);
      this.setState({
        muenList: res.data.list || []
      })
    })
  }
  getData2() {
    this.http.post('/api/menuedit', {pid:'3-4u6jdf', icon: '3-4ujioe;kr'})
    .then(res => {
      console.log(res);
    })
  }
  getData3() {
    // 通过fetch的get方法获取数据
    fetch('/api/menulist', {
      istree: 1
    })
      .then(res => {
        console.log(11, res);
        return res.json()
      })
      .then(res => {
        this.setState({
          muenList: res.list || []
        })
      })
  }
  getData4() {
    // 通过fetch的post方法获取数据
    fetch('/api/menuedit', {
      method: 'POST',
      // body中存放post的数据
      body: JSON.stringify({pid:'31-096dssdff', url: '/saldfjhul'})
    })
    .then(res => {
      return res.json()
    })
    .then(res => {
      console.log(res.msg);
    })
  }
  getData5() {
    myGet('/api/menulist')
    .then(res => {
      this.setState({
        muenList: res.list || []
      })
    })
  }
  getData6() {
    myPost('/api/menuedit', {pid: 'spea08tu', url: '/294385mn'})
    .then(res=>{
      console.log(res.msg);
    })
  }
  // 在生命周期中发请求
  componentDidMount() {
    this.getData3()
  }
  render() {
    return (
      <div>
        <p>axios使用示例</p>
        <button onClick={()=>this.getData1()}>获取数据-get</button>
        <button onClick={()=>this.getData2()}>获取数据-post</button>
        <button onClick={()=>this.getData3()}>fetch-get</button>
        <button onClick={()=>this.getData4()}>fetch-post</button>
        <button onClick={()=>this.getData5()}>fetch-封装的get</button>
        <button onClick={()=>this.getData6()}>fetch-封装的post</button>
        {
          this.state.muenList.map(item => {
            return (<p key={item.id}>
              {item.title}
            </p>)
          })
        }
      </div>
    )
  }
}
